package com.fortune.rainshine.system.service.impl;

import java.util.*;

import com.google.common.collect.Lists;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.fortune.rainshine.common.PageResult;
import com.fortune.rainshine.common.exception.BusinessException;
import com.fortune.rainshine.common.exception.ParameterException;
import com.fortune.rainshine.service.service.ShopService;
import com.fortune.rainshine.system.dao.RoleMapper;
import com.fortune.rainshine.system.dao.UserMapper;
import com.fortune.rainshine.system.dao.UserRoleMapper;
import com.fortune.rainshine.system.service.UserService;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.service.OrderModel;
import com.fortune.rainshinecommon.model.service.StockModel;
import com.fortune.rainshinecommon.model.system.Role;
import com.fortune.rainshinecommon.model.system.User;
import com.fortune.rainshinecommon.model.system.UserRole;
import com.fortune.rainshinecommon.util.EndecryptUtil;
import com.fortune.rainshinecommon.util.StringUtil;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private ShopService shopService;

	@Override
	public User getByUsername(String username) {
		return userMapper.getByUsername(username);
	}
	
	@Override
	public User getByNickname(String username) {
		return userMapper.getByNickname(username);
	}
	
	

	@Override
	public PageResult<User> list(int pageNum, int pageSize, boolean showDelete, String userName, String phone,
			User user) {
		List<User> userListTotal = new ArrayList<>();
		// 获取数据，默认按创建时间倒序排列
		List<User> userList = new ArrayList<>();

		List<Role> role = roleMapper.selectByUserId(user.getUserId());
		Integer roleId = role.get(0).getRoleId();
		// 参数封装
		Map<String, Object> map = new HashMap<>();

		// 判断角色显示那些用户
		// 判断为boss
		if (roleId == 1 || roleId == 2) {
			
			//查询总部管理员列表
			Wrapper<User> wrapper = new EntityWrapper<>();
			wrapper.ne("user_id", 1);
			List<User> adminList = userMapper.selectList(wrapper.orderBy("create_time", false));
			
			userListTotal.addAll(adminList);
			if(!adminList.isEmpty()){
				adminList.forEach(e->e.setParentId(-1));
			}
//			//查询招商人员列表
//			map.put("roleId", 4);
//			userList = userMapper.getUsersByMap(map);
//			userListTotal.addAll(userList);
//			if (!userList.isEmpty()) {
//				for (User one : userList) {
//					one.setParentId(-1);
//
//					// 获取招商下的所有门店店长数据
//					map.put("merchantsId", one.getUserId());
//					List<User> dianZhangList = userMapper.getMerchantsIdById(map);
//
//					if (dianZhangList != null && !dianZhangList.isEmpty()) {
//						for (User dian : dianZhangList) {
//							//dian.setParentId(one.getUserId());
//							one.setParentId(-1);
//							userListTotal.add(dian);
//
//							// 获取店长下的所有店员数据
//							map.put("dianZhang", dian.getUserId());
//							List<User> dianYuanList = userMapper.getDianYuanListByCode(map);
//                            if(dianYuanList != null && !dianYuanList.isEmpty()) {
//                            	for (User dianYuan : dianYuanList) {
//    								//dianYuan.setParentId(dian.getUserId());
//    								one.setParentId(-1);
//    								userListTotal.add(dianYuan);
//    							}
//                            }
//							
//						}
//					}
//				}
//			}
		}
		// 判断为招商
		else if (roleId == 4) {
			// 获取招商下的所有门店店长数据
			map.put("merchantsId", user.getUserId());
			List<User> dianZhangList = userMapper.getMerchantsIdById(map);
			
			if (dianZhangList != null && !dianZhangList.isEmpty()) {
				for (User dian : dianZhangList) {
					dian.setParentId(-1);
					userListTotal.add(dian);

					// 获取店长下的所有店员数据
					map.put("dianZhang", dian.getUserId());
					List<User> dianYuanList = userMapper.getDianYuanListByCode(map);
					if(dianYuanList != null && !dianYuanList.isEmpty()){
						for (User dianYuan : dianYuanList) {
							dianYuan.setParentId(-1);
							userListTotal.add(dianYuan);
						}
					}
					
				}
			}
		}
		// 判断为店长
		else if (roleId == 5) {
			// 获取店长下的所有店员数据
			//map.put("dianZhang", user.getUserId());
			map.put("shopId", user.getShopId());
			List<User> dianYuanList = userMapper.getDianYuanListByCode(map);
			if(dianYuanList != null && !dianYuanList.isEmpty()){
				for (User dianYuan : dianYuanList) {
					dianYuan.setParentId(-1);
					userListTotal.add(dianYuan);
				}
			}
		}

		//用户总数
		int totalNum = 0;
		if (!userListTotal.isEmpty()) { // 查询user的角色 List<UserRole>
			List<UserRole> userRoles = userRoleMapper.selectByUserIds(getUserIds(userListTotal));
			
			Iterator<User> iterator = userListTotal.iterator();
	        while (iterator.hasNext()) {
	        	User integer = iterator.next();
//	        	System.out.println(integer.getUserId());
	        	totalNum++;
	        	List<Role> tempURs = new ArrayList<>();
	        	userRoles.stream().forEach(e -> {
	        		if (integer.getUserId().equals(e.getUserId())) {
						tempURs.add(new Role(e.getRoleId(), e.getRoleName()));
					}
	        	});
	        	integer.setRoles(tempURs);
        		integer.setRoleName(tempURs.get(0).getRoleName());
        		
	        	if(StringUtil.isNotBlank(userName) || StringUtil.isNotBlank(phone)) {
	        		boolean ifRemove = false;
	        		if(!integer.getNickName().contains(userName.trim())) {
	        			ifRemove = true;
	        		}
	        		if(!integer.getPhone().contains(phone.trim())) {
	        			ifRemove = true;
	        		}
	        		if(ifRemove) {
	        			iterator.remove();
	        		}
	        		totalNum = userListTotal.size();
	        	}        
	        }

			/*
			 * for (User one : userListTotal) { totalNum++; List<Role> tempURs = new
			 * ArrayList<>(); for (UserRole ur : userRoles) { if
			 * (one.getUserId().equals(ur.getUserId())) { tempURs.add(new
			 * Role(ur.getRoleId(), ur.getRoleName())); } } one.setRoles(tempURs);
			 * one.setRoleName(tempURs.get(0).getRoleName()); }
			 */
		}
		List<User> listNew = new ArrayList<>();
		int endNUm = ((pageNum-1)*pageSize)+pageSize > totalNum ? totalNum :((pageNum-1)*pageSize)+pageSize;
		listNew = userListTotal.subList((pageNum-1)*pageSize, endNUm);
		return new PageResult<>(totalNum, listNew);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean add(User user, Integer merchantsId) throws BusinessException {
		if (userMapper.getByUsername(user.getUsername()) != null) {
			throw new BusinessException("帐号名称已经存在!");
		}
		if (userMapper.getByPhone(user.getPhone()) != null) {
			throw new BusinessException("电话号码已被使用！");
		}
		user.setPassword(EndecryptUtil.encrytMd5(user.getPassword(), user.getUsername(), 3));
		user.setState(0);
		user.setCreateTime(new Date());
		boolean rs = userMapper.insert(user) > 0;

		if (rs) {
			List<Integer> roleIds = getRoleIds(user.getRoles());
			if (userRoleMapper.insertBatch(user.getUserId(), roleIds, user.getCreateId(), user.getUpdateId()) < roleIds.size()) {
				throw new BusinessException("添加失败，请重试");
			}
			// 判断增加用户为招商
			if (user.getRoles().get(0).getRoleId() == 4) {
				ShopModel shop = new ShopModel("招商" + "(" + user.getNickName() + ")", user.getUserId(), merchantsId,
						(byte) 1);
				shop.setUser(user);
				shop.setShopLevel(2);
				if (shopService.add(shop).getCode() != 1) {
					throw new BusinessException("添加失败，请重试");
				}
			}
			// 判断增加用户为boss
			if (user.getRoles().get(0).getRoleId() == 2) {
				ShopModel shop = new ShopModel("总店", user.getUserId(), (byte) 1);
				shop.setUser(user);
				shop.setShopLevel(1);
				if (shopService.add(shop).getCode() != 1) {
					throw new BusinessException("添加失败，请重试");
				}
			}
		}
		return rs;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean update(User user) {
		User oldUser = userMapper.getByUsername(user.getUsername());
		if(!oldUser.getPhone().equals(user.getPhone())){
			if (userMapper.getByPhone(user.getPhone()) != null) {
				throw new BusinessException("电话号码已被使用！");
			}
		}
		user.setUsername(null);
		boolean rs = userMapper.updateById(user) > 0;
//		if (rs) {
//			userRoleMapper.delete(new EntityWrapper().eq("user_id", user.getUserId()));
//			List<Integer> roleIds = getRoleIds(user.getRoles());
//			if (userRoleMapper.insertBatch(user.getUserId(), roleIds, user.getCreateId(), user.getUpdateId()) < roleIds.size()) {
//				throw new BusinessException("修改失败，请重试");
//			}
//		}
		return rs;
	}

	/**
	 * 添加用户角色
	 */
	private List<Integer> getRoleIds(List<Role> roles) {
		List<Integer> rs = new ArrayList<>();
		if (roles != null && roles.size() > 0) {
			for (Role role : roles) {
				rs.add(role.getRoleId());
			}
		}
		return rs;
	}

	@Override
	public boolean updateState(Integer userId, int state) throws ParameterException {
		if (state != 0 && state != 1) {
			throw new ParameterException("state值需要在[0,1]中");
		}
		User user = new User();
		user.setUserId(userId);
		user.setState(state);
		return userMapper.updateById(user) > 0;
	}

	@Override
	public boolean updatePsw(Integer userId, String username, String password) {
		User user = new User();
		user.setUserId(userId);
		user.setPassword(EndecryptUtil.encrytMd5(password, username, 3));
		return userMapper.updateById(user) > 0;
	}

	@Override
	public User getById(Integer userId) {
		return userMapper.selectById(userId);
	}

	@Override
	public boolean delete(Integer userId) {
		return userMapper.deleteById(userId) > 0;
	}

	private List<Integer> getUserIds(List<User> userList) {
		List<Integer> userIds = new ArrayList<>();
		for (User one : userList) {
			userIds.add(one.getUserId());
		}
		return userIds;
	}

	@Override
	public List<User> getUsersByRole(String parm) {
		Integer roleId = roleMapper.selectIdByRoleName(parm);
		List<User> users = userMapper.getUsersByRole(roleId);
		return users;
	}

	@Override
	public List<User> getShopAssistant(Integer userId,String shopId,boolean state) {
		List<User> users = new ArrayList<>();
		try {
			Wrapper<User> wrapper = new EntityWrapper<>();
        	wrapper.eq("create_id", userId);
        	wrapper.eq("shop_id", shopId);
        	if(state) {
        		wrapper.eq("state", 0);
        	}
			users = userMapper.selectList(wrapper);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return users;
	}

	@Override
	public User getByUserPhone(String searchValue) {
		
		return userMapper.getByPhone(searchValue);
	}
}
